import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:material_collection_app/widget/common/refresh.dart';
import 'package:material_collection_app/widget/common/tabbar_custom_return.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class OutDqdPage extends StatefulWidget {
  final Map arguments;
  OutDqdPage({Key key, this.arguments}) : super(key: key);

  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<OutDqdPage> {
  Map outInfo = {};
  List outList = [];
  int wareTotal = 0;
  List progressList = [];
  String baseApi = 'goodsOut/';
  String actionModel = '';

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    String model = widget.arguments['item']['model'];

    setState(() {
      actionModel = model;
    });

    if (model == 'scrap') {
      setState(() {
        baseApi = 'ScrapGoodsOut/';
      });
    } else if (model == 'allocate') {
      setState(() {
        baseApi = 'AllocateGoodsOut/';
      });
    } else {
      setState(() {
        baseApi = 'GoodsOut/';
      });
    }
    print(widget.arguments['item']['model']);
    _getOutInfo();
    getProgressList();
  }

  Widget _buildCardHead(title) {
    return Container(
      width: 680.w,
      height: 90.w,
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
          border:
              Border(bottom: BorderSide(width: 1, color: Color(0xFFF1F1F1)))),
      child: Text(
        title,
        style: TextStyle(
            color: Color(0xFF333333),
            fontSize: 16,
            fontWeight: FontWeight.bold),
      ),
    );
  }

  // 入库信息
  Widget _buildOutPage() {
    if (outInfo['out_code'] != null) {
      return Container(
        padding: EdgeInsets.fromLTRB(24.w, 20.w, 24.w, 0),
        child: Column(
          children: <Widget>[
            _buildRowText('出库单号', outInfo['out_code']),
            _buildRowText('案件编号', outInfo['code']),
            _buildRowText('出库名称', outInfo['title']),
            _buildRowText('申请人', outInfo['handleGroup']),
            _buildRowText('来源部门', outInfo['handleGroupDepartment']),
            _buildRowText('申请时间', outInfo['create_time']),
            _buildRowText('状态', outInfo['show_status'], Color(0xFFF54745)),
            _buildRowText('备注', outInfo['business_group']),
          ],
        ),
      );
    } else {
      return Container();
    }
  }

  Widget _buildRowText(title, text, [Color color]) {
    return Padding(
      padding: EdgeInsets.fromLTRB(0, 15.w, 0, 15.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(title.toString(),
              style: TextStyle(color: Color(0xFF999999), fontSize: 14)),
          Text(text.toString(),
              style:
                  TextStyle(color: color ?? Color(0xFF333333), fontSize: 14)),
        ],
      ),
    );
  }

  // 下拉刷新
  void _onRefresh() async {
    _getOutInfo();
    _refreshController.loadComplete();

    await Future.delayed(Duration(milliseconds: 600));
    _refreshController.refreshCompleted();
  }

  // 获取出库物资信息
  void _getOutInfo() {
    Map item = widget.arguments['item'];
    int id = item['out_id'];

    DioUtils.request("${baseApi}detail",
        context: context, method: "POST", params: {'id': id}, onSuccess: (res) {
      if (res['code'] == 1) {
        setState(() {
          outInfo = res['data'];
          outList = res['data']['goods'];
          wareTotal = res['data']['goods'].length;
        });
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 获取工单进度
  void getProgressList() {
    Map item = widget.arguments['item'];
    int id = item['out_id'];

    DioUtils.request("${baseApi}logs",
        context: context,
        method: "POST",
        params: {
          'out_id': {'id': id},
          'limit': 1000
        }, onSuccess: (res) {
      if (res['code'] == 1) {
        setState(() {
          progressList = res["data"]["data"];
        });
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 状态栏状态文字转换
  String getStatusTex(int status, String statusText, int receptorId) {
    // 待接收
    if (status == 0 && receptorId == 0) {
      return '待接收';
    } else if (status == 10 && receptorId == 1) {
      return '已清点';
    } else {
      return statusText;
    }
  }

  Widget _buildPageOne() {
    return SingleChildScrollView(
        padding: EdgeInsets.fromLTRB(25.w, 30.w, 25.w, 50.w),
        child: Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: 700.w,
                margin: EdgeInsets.only(top: 24.w),
                padding: EdgeInsets.only(bottom: 34.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20.w),
                ),
                child: Column(
                  children: <Widget>[_buildCardHead('基本信息'), _buildOutPage()],
                ),
              )
            ],
          ),
        ));
  }

  Widget _buildPageTwo() {
    return Container(
        color: Utils.hexToColor('#F5F6FA'),
        padding: EdgeInsets.fromLTRB(25.w, 23.w, 25.w, 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(bottom: 15.w),
              child: Align(
                  alignment: Alignment.centerLeft,
                  child: Row(
                    children: <Widget>[
                      Text(
                        '共有',
                        style: TextStyle(
                            color: Utils.hexToColor('#999999'), fontSize: 12),
                      ),
                      Text(
                        wareTotal.toString(),
                        style: TextStyle(
                            color: Utils.hexToColor('#297CFF'), fontSize: 12),
                      ),
                      Text(
                        '个物资',
                        style: TextStyle(
                            color: Utils.hexToColor('#999999'), fontSize: 12),
                      ),
                    ],
                  )),
            ),
            Expanded(
                flex: 1,
                child: Refresh(
                  refreshController: _refreshController,
                  onRefresh: _onRefresh,
                  enablePullUp: false,
                  child: ListView.builder(
                      itemCount: outList.length,
                      padding: EdgeInsets.only(bottom: 60.w),
                      itemBuilder: (BuildContext context, int index) {
                        var item = outList[index];

                        item['actionModel'] = actionModel;

                        return GestureDetector(
                          onTap: () {
                            Navigator.pushNamed(context, "/out_detail",
                                arguments: {'item': item});
                          },
                          child: Container(
                            width: 700.w,
                            height: 210.w,
                            margin: EdgeInsets.only(
                                top: index == 0 ? 20.w : 0, bottom: 16.w),
                            padding: EdgeInsets.fromLTRB(24.w, 30.w, 24.w, 0.w),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(20.w),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Padding(
                                  padding: EdgeInsets.only(bottom: 5.w),
                                  child: Text(item['goods_name'],
                                      style: TextStyle(
                                          color: Color(0xFF333333),
                                          fontSize: 15,
                                          fontWeight: FontWeight.bold,
                                          height: 1)),
                                ),
                                Row(
                                  // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: <Widget>[
                                    Container(
                                      width: 300.w,
                                      margin: EdgeInsets.only(top: 18.w),
                                      child: Text('物资分类：' + item['type_name'],
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              color: Color(0xFF666666),
                                              fontSize: 12,
                                              height: 1)),
                                    ),
                                    // 注意：这条记录只有在已清点才会显示
                                    Container(
                                      width: 300.w,
                                      margin: EdgeInsets.only(
                                          left: 30.w, top: 18.w),
                                      child: Row(
                                        children: <Widget>[
                                          Text('RFID号：',
                                              style: TextStyle(
                                                  color: Color(0xFF666666),
                                                  fontSize: 12,
                                                  height: 1)),
                                          Expanded(
                                            child: Text(item['rfid_code'],
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                    color: Color(0xFF666666),
                                                    fontSize: 12,
                                                    height: 1)),
                                          )
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                                Row(
                                  children: <Widget>[
                                    Container(
                                      width: 300.w,
                                      margin: EdgeInsets.only(top: 13.w),
                                      child: Text(
                                          '物资数量：' + item['num'].toString(),
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              color: Color(0xFF666666),
                                              fontSize: 12,
                                              height: 1)),
                                    ),
                                    Container(
                                      width: 300.w,
                                      margin: EdgeInsets.only(
                                          left: 30.w, top: 13.w),
                                      child: Text('所属仓库：' + item['store_name'],
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              color: Color(0xFF666666),
                                              fontSize: 12,
                                              height: 1)),
                                    ),
                                  ],
                                ),
                                Row(
                                  children: <Widget>[
                                    Container(
                                      width: 300.w,
                                      margin: EdgeInsets.only(top: 13.w),
                                      child: Text(
                                          '所属库区：' + item['store_library_name'],
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              color: Color(0xFF666666),
                                              fontSize: 12,
                                              height: 1)),
                                    ),
                                    Container(
                                      width: 300.w,
                                      margin: EdgeInsets.only(
                                          left: 30.w, top: 13.w),
                                      child: Text(
                                          '所属库位：' + item['store_detail_code'],
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              color: Color(0xFF666666),
                                              fontSize: 12,
                                              height: 1)),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        );
                      }),
                ))
          ],
        ));
  }

  Widget _buildPageThree() {
    return Container(
        color: Colors.white,
        padding: EdgeInsets.fromLTRB(25.w, 23.w, 25.w, 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Expanded(
                flex: 1,
                child: ListView.builder(
                    itemCount: progressList.length,
                    padding: EdgeInsets.only(bottom: 60.w),
                    itemBuilder: (BuildContext context, int index) {
                      var item = progressList[index];

                      return GestureDetector(
                        onTap: () {},
                        child: Container(
                            width: 700.w,
                            height: 120.w,
                            padding: EdgeInsets.fromLTRB(0.w, 0.w, 24.w, 0.w),
                            child: Stack(
                              children: <Widget>[
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Row(
                                      children: <Widget>[
                                        Container(
                                          width: 630.w,
                                          margin: EdgeInsets.only(top: 10.w),
                                          padding: EdgeInsets.only(
                                              left: 43.w, bottom: 5.w),
                                          child: Text(
                                              item['user__name'] +
                                                  '、' +
                                                  item['show_action']
                                                      .toString(),
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                  color: Color(0xFF333333),
                                                  fontSize: 15,
                                                  fontWeight: FontWeight.bold,
                                                  height: 1)),
                                        ),
                                      ],
                                    ),
                                    Padding(
                                      padding: EdgeInsets.only(
                                          left: 40.w, top: 13.w),
                                      child: Text(item['create_time'],
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                              color: Color(0xFF666666),
                                              fontSize: 12,
                                              height: 1)),
                                    )
                                  ],
                                ),
                                Container(
                                  width: 2.w,
                                  height: 120.w,
                                  // color: Utils.hexToColor('#000000'),
                                  color: Utils.hexToColor('#F2F2F2'),
                                  margin: EdgeInsets.fromLTRB(13.w, 0, 0, 0),
                                ),
                                Container(
                                  width: 28.w,
                                  height: 28.w,
                                  margin: EdgeInsets.fromLTRB(0, 10.w, 0, 0),
                                  decoration: BoxDecoration(
                                      color: Utils.hexToColor('#409EFF'),
                                      borderRadius: BorderRadius.circular(32.w),
                                      border: Border.all(
                                          color: Utils.hexToColor('#E0EFFF'),
                                          width: 2)),
                                ),
                                Offstage(
                                  offstage: index == 0 ? false : true,
                                  child: Container(
                                    width: 6.w,
                                    height: 10.w,
                                    color: Colors.white,
                                    margin:
                                        EdgeInsets.fromLTRB(12.w, 0.w, 0, 0),
                                  ),
                                )
                              ],
                            )),
                      );
                    }))
          ],
        ));
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return DefaultTabController(
        length: 3,
        initialIndex: 0,
        child: Scaffold(
            appBar: AppBar(
                backgroundColor: Utils.hexToColor('#297CFF'),
                bottom: PreferredSize(
                  preferredSize: Size(double.infinity, 0),
                  child: TabBarCustomReturn(
                    tabs: ['出库信息', '出库物资', '工单进度'],
                    indicatorInsets: EdgeInsets.fromLTRB(26, 0, 26, 4),
                  ),
                )),
            body: TabBarView(children: <Widget>[
              _buildPageOne(),
              _buildPageTwo(),
              _buildPageThree(),
            ])));
  }
}
